package com.iap.admin.mediator
{
	import com.iap.common.event.FavoriteEvent;
	import com.iap.common.event.SampleEvent;
	import com.iap.common.signal.FavoriteRequestSignal;
	import com.iap.common.signal.SampleRequestSignal;
	import com.iap.admin.view.FavoriteView;
	import com.iap.admin.view.favorite.FavoriteEditView;
	import com.iap.admin.view.favorite.code.FavoriteEditViewCode;
	import com.iap.app.AppGlobal;
	import com.iap.app.StatusCode;
	import com.iap.app.model.ServiceResponse;
	import com.iap.common.model.Favorite;
	import com.iap.common.model.Sample;
	
	import mx.collections.ArrayCollection;
	
	import spark.components.Group;
	import com.iap.common.mediator.BaseMediator;

	public class FavoriteEditMediator extends BaseMediator
	{
		[Inject]
		public var view:FavoriteEditView;
		[Inject]
		public var request:FavoriteRequestSignal;
		[Inject]
		public var sampleRequest:SampleRequestSignal;
		
		override public function onRegister():void
		{
			view.onCancel.add(onCancel);
			view.onSubmit.add(onSubmit);
			addContextListener(FavoriteEvent.RESPONSE, responseHandler);
			addContextListener(SampleEvent.RESPONSE, sampleResponseHandler);
			dispatchInitRequest();
		}

		private function dispatchInitRequest():void
		{
			AppGlobal.startWait();
			sampleRequest.dispatch(new Sample(), SampleRequestSignal.GET);
		}
		
		private function onCancel(itemName:String):void
		{
			switch(itemName)
			{
				case FavoriteEditViewCode.CANCEL_NAME:
				{
					optionBack();
					break;
				}
			}
		}
		
		private function optionBack():void
		{
			setView(view.parent as Group, new FavoriteView(), FX_GLIDE_OUT);
		}
		
		private function onSubmit(model:Favorite, task:String):void
		{
			AppGlobal.startWait();
			request.dispatch(model, task);
		}
		
		private function responseHandler(evt:FavoriteEvent):void
		{
			AppGlobal.endWait();
			var response:ServiceResponse = evt.response;
			if(response.task == FavoriteRequestSignal.SAVE)
			{
				if(!view.canCloseForm)
					return;
			}
			if(response.status.code == StatusCode.OK || view.canCloseForm)
				optionBack();
		}

		private function sampleResponseHandler(evt:SampleEvent):void
		{
			AppGlobal.endWait();
			if(evt.response.status.code != StatusCode.OK) return;
			var response:ServiceResponse = evt.response;
			setSampleList(new ArrayCollection(response.result as Array));
		}

		private function setSampleList(items:ArrayCollection):void
		{
			view.sampleSelectForm.dataProvider = items;
			if(view.model == null) return;
			var item:Favorite = view.model as Favorite;
			if(item.sample == null) return;
			for(var i:Number = 0; i<items.length; i++)
			{
				if((items[i] as Sample).id == item.sample.id)
				{
					view.sampleSelectForm.selectedIndex = i;
					view.updateVisorFromModel();
				}
			}
		}
	}
}